package com.talent.service.file.controller;

import com.talent.service.file.config.MinioConfig;
import com.talent.service.file.service.IMinioService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @ClassName：MinioController
 * @Author: hszhou
 * @Date: 2025/1/7 13:20
 * @Description: 必须描述类做什么事情, 实现什么功能
 */

@RestController
@RequestMapping("/oss")
public class MinioController {

    private static final Logger logger = LoggerFactory.getLogger(MinioController.class);

    @Autowired
    private IMinioService minioService;

    @Autowired
    private MinioConfig minioConfig;


    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {

            minioService.uploadFile(minioConfig.getBucket(), file);
            return "上传成功";
        } catch (Exception e) {
            logger.error("上传失败");
            return "上传失败";
        }
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @DeleteMapping("/")
    public void delete(@RequestParam("fileName") String fileName) {
        minioService.removeFile(minioConfig.getBucket(), fileName);
    }

    /**
     * 获取文件信息
     *
     * @param fileName
     * @return
     */
//    @GetMapping("/info")
//    public String getFileStatusInfo(@RequestParam("fileName") String fileName) {
//        return minioService.getFileStatusInfo(minioConfig.getBucket(), fileName);
//    }

    /**
     * 获取文件外链
     *
     * @param fileName
     * @return
     */
    @GetMapping("/url")
    public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
        return minioService.getPresignedObjectUrl(minioConfig.getBucket(), fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream fileInputStream = minioService.getObject(minioConfig.getBucket(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载失败");
        }
    }

}
